import D2Ext

from .CResource import CResource
from .CWidget import CWidget


class CPanel(CWidget):

    def __init__(self, parent=None):
        super(CPanel, self).__init__(parent)
        self.image_file = None
        self.frame_start = 0
        self.frame_end = 0

    def set_image(self, image_file, frame_start, frame_end):
        self.image_file = CResource.get_image(image_file)
        self.frame_start = frame_start
        self.frame_end = frame_end

    def draw(self):
        if not self.image_file:
            return

        width = D2Ext.View_GetWindowWidth()
        height = D2Ext.View_GetWindowHeight()

        starty = (height - (480 - 352)) / 2 - 352/2
        startx = width - D2Ext.View_GetWindowStartX() - 320
        self.set_position(int(startx), int(starty))

        curr_x = self.dx
        curr_y = self.dy

        for frame in xrange(self.frame_start, self.frame_end):

            D2Ext.LogMsg("CPanel.draw, frame=%d, curr_x=%s, curr_y=%s" % (frame, curr_x, curr_y))

            fh = D2Ext.Image_GetHeight(self.image_file, frame)
            D2Ext.Image_SetFrame(self.image_file, frame)
            D2Ext.Image_Draw(self.image_file, curr_x, curr_y + fh, self.opacity)

            if frame % 2 == 0:
                curr_x = self.dx + 256
            else:
                curr_x = self.dx
                curr_y = curr_y + int((frame + 1) / 2) * 256

                # fh = D2Ext.Image_GetHeight(self.image_file, frame)
                # oy = D2Ext.Image_GetYOffset(self.image_file, frame)
                # curr_y = curr_y + oy + fh
